import { io, Socket } from 'socket.io-client';
import { store } from '../store/store';
import { 
  setCurrentGame, 
  setAvailableGames, 
  addPlayerToGame, 
  removePlayerFromGame,
  updatePlayerChips,
  setCommunityCards,
  updateGamePhase,
  updatePot,
  updateCurrentBet,
  setCurrentPlayerPosition,
  setIsPlayerTurn,
  updatePlayerActions
} from '../store/gameSlice';

// Socket.IO客户端类
class SocketService {
  private socket: Socket | null = null;
  private isConnected = false;

  // 连接到服务器
  connect(token: string): void {
    if (this.socket && this.isConnected) {
      return;
    }

    const serverUrl = process.env.REACT_APP_SOCKET_URL || 'http://localhost:3001';
    
    this.socket = io(serverUrl, {
      auth: {
        token
      }
    });

    // 设置事件监听器
    this.setupEventListeners();
  }

  // 断开连接
  disconnect(): void {
    if (this.socket) {
      this.socket.disconnect();
      this.socket = null;
      this.isConnected = false;
    }
  }

  // 设置事件监听器
  private setupEventListeners(): void {
    if (!this.socket) return;

    // 连接成功
    this.socket.on('connect', () => {
      console.log('Connected to server');
      this.isConnected = true;
    });

    // 连接断开
    this.socket.on('disconnect', () => {
      console.log('Disconnected from server');
      this.isConnected = false;
    });

    // 连接错误
    this.socket.on('connect_error', (error) => {
      console.error('Connection error:', error);
      this.isConnected = false;
    });

    // 获取可用游戏列表
    this.socket.on('games:list', (games) => {
      store.dispatch(setAvailableGames(games));
    });

    // 游戏状态更新
    this.socket.on('game:state', (gameState) => {
      store.dispatch(setCurrentGame(gameState));
    });

    // 玩家加入游戏
    this.socket.on('game:player_joined', (player) => {
      store.dispatch(addPlayerToGame(player));
    });

    // 玩家离开游戏
    this.socket.on('game:player_left', (playerId) => {
      store.dispatch(removePlayerFromGame(playerId));
    });

    // 玩家筹码更新
    this.socket.on('game:chips_updated', ({ playerId, chips }) => {
      store.dispatch(updatePlayerChips({ playerId, chips }));
    });

    // 公共牌更新
    this.socket.on('game:community_cards', (cards) => {
      store.dispatch(setCommunityCards(cards));
    });

    // 游戏阶段更新
    this.socket.on('game:phase', (phase) => {
      store.dispatch(updateGamePhase(phase));
    });

    // 底池更新
    this.socket.on('game:pot', (pot) => {
      store.dispatch(updatePot(pot));
    });

    // 当前下注额更新
    this.socket.on('game:current_bet', (bet) => {
      store.dispatch(updateCurrentBet(bet));
    });

    // 当前玩家位置更新
    this.socket.on('game:current_player', (position) => {
      store.dispatch(setCurrentPlayerPosition(position));
      
      // 检查是否是当前玩家的回合
      const state = store.getState();
      const currentGame = state.game.currentGame;
      const authUser = state.auth.user;
      
      if (currentGame && authUser) {
        const currentPlayer = currentGame.players[position];
        const isPlayerTurn = currentPlayer && currentPlayer.id === authUser.id;
        store.dispatch(setIsPlayerTurn(isPlayerTurn));
        
        // 如果是当前玩家的回合，更新可用动作
        if (isPlayerTurn) {
          // 这里应该从服务器获取可用动作，暂时使用默认值
          store.dispatch(updatePlayerActions({
            canCheck: true,
            canCall: true,
            canRaise: true,
            canFold: true,
            canAllIn: true,
          }));
        }
      }
    });

    // 玩家可用动作更新
    this.socket.on('game:player_actions', (actions) => {
      store.dispatch(updatePlayerActions(actions));
    });
  }

  // 加入游戏房间
  joinGame(gameId: string): void {
    if (this.socket && this.isConnected) {
      this.socket.emit('game:join', { gameId });
    }
  }

  // 离开游戏房间
  leaveGame(gameId: string): void {
    if (this.socket && this.isConnected) {
      this.socket.emit('game:leave', { gameId });
    }
  }

  // 执行游戏动作
  makeAction(gameId: string, action: string, amount?: number): void {
    if (this.socket && this.isConnected) {
      this.socket.emit('game:action', { gameId, action, amount });
    }
  }

  // 开始游戏
  startGame(gameId: string): void {
    if (this.socket && this.isConnected) {
      this.socket.emit('game:start', { gameId });
    }
  }

  // 获取连接状态
  getConnectionStatus(): boolean {
    return this.isConnected;
  }
}

// 创建单例实例
const socketService = new SocketService();

export default socketService;